package com.spring.dao.impl;

import com.spring.dao.AccountDao;
import com.spring.pojo.Account;
import com.spring.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author SpringWang
 * @date 2021/5/19
 */
public class AccountDaoImpl implements AccountDao {

    @Override
    public Account findByCardNo(String cardNo) throws Exception {
        Connection connection = ConnectionUtils.getInstance().getCurrentThreadConn();
        String sql = "select * from account where card_no=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()) {
            account.setName(resultSet.getString("name"));
            account.setBalance(resultSet.getInt("balance"));
            account.setCardNo(resultSet.getString("card_no"));
        }
        resultSet.close();
        preparedStatement.close();

        return account;
    }

    @Override
    public void updateBalanceByCardNo(Account account) throws Exception {
//        DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
        Connection connection = ConnectionUtils.getInstance().getCurrentThreadConn();
        String sql = "update account set balance=? where card_no=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, account.getBalance());
        preparedStatement.setString(2, account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
    }
}
